<template>
  <div class="com-container">
    <div class="com-chart" ref="seller_ref"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      // echarts实例对象
      chartInstance: null,
      // 服务器获取所有的数据
      allData: [],
      currentPage: 1, // 当前页数
      totalPage: 0, // 总页数 每页显示5个条目
      timerId: null, //  定时器标识
    };
  },
  created () {
    // 在组件创建完成之后 进行回调函数的注册
    this.$socket.registerCallBack('sellerData', this.getData)
  },
  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'sellerData',
      chartName: 'seller',
      value: ''
    })
    // 对窗口大小变化的事件进行监听
    window.addEventListener("resize", this.screenAdapter);
    this.screenAdapter();
  },
  destroyed() {
    clearInterval(this.timerId); // 在组件销毁的时候, 需要将监听器取消掉
    window.removeEventListener("resize", this.screenAdapter);
    // 在组件销毁的时候, 进行回调函数的取消
    this.$socket.unRegisterCallBack('rankData')
  },
  methods: {
    initChart() {
      // 初始化echarts实例对象
      this.chartInstance = this.$echarts.init(this.$refs.seller_ref, this.theme);
      // 初始化图表配置项，和数据无关
      const initOption = {
        title: {
          text: "▎ 商家销量排行",
          left: 20,
          top: 20,
          textStyle: {
            color: "#fff",
          },
        },
        grid: {
          top: "20%",
          left: "3%",
          right: "6%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "line",
            z: 0,
            lineStyle: {
              // width: 66,
              color: "#2d3443",
            },
          },
        },
        series: [
          {
            type: "bar",
            label: {
              show: true,
              position: "right",
              textStyle: { color: "#fff" },
            },
            // barWidth: 66,
            itemStyle: {
              // barBorderRadius: [0, 33, 33, 0],
              color: new this.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: "#5052EE" },
                { offset: 1, color: "#AB6EE5" },
              ]),
            },
          },
        ],
      };
      this.chartInstance.setOption(initOption);
      this.chartInstance.on("mouseover", () => {
        clearInterval(this.timerId);
      });
      this.chartInstance.on("mouseout", () => {
        this.startInterval();
      });
    },
    async getData(res) {
      // const { data: res } = await this.$http.get("seller");
      // console.log(res);
      this.allData = res;
      // 对allData进行从小到大的排序
      this.allData.sort((a, b) => {
        return a.value - b.value;
      });
      // console.log(this.allData);
      // 计算总页数
      this.totalPage =
        this.allData.length % 5 === 0
          ? parseInt(this.allData.length / 5)
          : parseInt(this.allData.length / 5) + 1;
      this.updateChart();
      // 开启动画
      this.startInterval();
    },
    updateChart() {
      // 分页处理，每5个元素显示一页
      const start = (this.currentPage - 1) * 5;
      const end = this.currentPage * 5;
      const showData = this.allData.slice(start, end);
      // 处理数据并且更新界面图表
      const sellerNames = showData.map((item) => {
        return item.name;
      });
      const sellerValues = showData.map((item) => {
        return item.value;
      });
      // 拥有数据之后的配置项
      const dataOption = {
        xAxis: {
          // 固定x的最大值
          max: this.allData[this.allData.length - 1].value,
        },
        yAxis: {
          data: sellerNames,
        },
        series: [
          {
            data: sellerValues,
          },
        ],
      };
      this.chartInstance.setOption(dataOption);
    },
    startInterval() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        this.currentPage++;
        if (this.currentPage > this.totalPage) {
          this.currentPage = 1;
        }
        this.updateChart();
      }, 3000);
    },
    // 当浏览器的大小发生变化的时候, 会调用的方法, 来完成屏幕的适配
    screenAdapter() {
      // console.log(this.$refs.seller_ref.offsetWidth)
      const titleFontSize = (this.$refs.seller_ref.offsetWidth / 100) * 3.6;
      // 和分辨率大小相关的配置项
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize,
          },
        },
        tooltip: {
          axisPointer: {
            lineStyle: {
              width: titleFontSize,
            },
          },
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              barBorderRadius: [0, titleFontSize/2, titleFontSize/2, 0],
            },
          },
        ],
      };
      this.chartInstance.setOption(adapterOption); // 手动的调用图表对象的resize 才能产生效果
      this.chartInstance.resize();
    },
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme () {
      this.chartInstance.dispose() // 销毁当前的图表
      this.initChart() // 重新以最新的主题名称初始化图表对象
      this.screenAdapter() // 完成屏幕的适配
      this.updateChart() // 更新图表的展示
    }
  }
};
</script>

<style lang="less" scoped>
// git remote add origin git@gitee.com:Zoe_x/vision.git
// git push -u origin "master"
</style>